<template>
  <view class="order-list-page">
    <view class="status-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: currentStatus === tab.value }"
        @tap="switchTab(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <view class="order-list" v-if="orders.length > 0">
      <view
        v-for="order in filteredOrders"
        :key="order.orderId"
        class="order-item"
        @tap="goToDetail(order.orderId)"
      >
        <view class="order-header">
          <text class="merchant">商家：{{ getMerchantName(order.merchantId) }}</text>
          <text class="status">{{ getStatusText(order.orderStatus) }}</text>
        </view>

<!--        <view class="order-goods-placeholder">
          <text class="goods-desc">共 {{ getOrderItemCount(order) }} 件商品</text>
        </view> -->

        <!-- 收货信息 -->
        <view class="order-receiver-info">
          <text class="receiver-line">收货人：{{ order.receiveName || '—' }}</text>
          <text class="receiver-line">电话：{{ order.receivePhone || '—' }}</text>
          <text class="receiver-line">地址：{{ order.receiveAddress || '—' }}</text>
		  <text class="receiver-line">订单编号：{{ order.orderId || '—' }}</text>
        </view>

        <!-- 时间信息 -->
        <view class="order-time-info">
          <text class="time-line">下单时间：{{ formatTime(order.createTime) }}</text>
          <text class="time-line">更新时间：{{ formatTime(order.updateTime) }}</text>
        </view>

        <view class="order-footer">
          <text class="total">实付：¥{{ (order.totalAmount + order.freight).toFixed(2) }}</text>
          <view class="action-buttons">
            <button
              v-if="order.orderStatus === 0"
              size="mini"
              type="primary"
              @tap.stop="handleSettle(order.orderId)"
            >
              立即支付
            </button>
            <button
              v-else-if="order.orderStatus === 1"
              size="mini"
              @tap.stop="confirmReceive(order.orderId)"
            >
              确认收货
            </button>
            <button
              v-else-if="order.orderStatus === 2"
              size="mini"
              @tap.stop="goToReview(order.orderId)"
            >
              去评价
            </button>
            <button
              v-else
              size="mini"
              disabled
            >
              {{ getStatusText(order.orderStatus) }}
            </button>
            <!-- 新增：查看详情按钮 -->
            <button size="mini" @tap.stop="logOrderId(order.orderId)">
              查看详情
            </button>
          </view>
        </view>
      </view>
    </view>

    <view v-else class="empty-tip">
      <text>暂无{{ currentStatusLabel }}订单</text>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getOrderList,settleOrder,confirmOrder  } from '@/api/Productapi.js';
import userManager from '@/common/utils/user.js';
import { orderCache } from '@/common/utils/orderCache.js'

// 订单状态映射
const statusMap = {
  0: '待付款',
  1: '待收货',
  2: '待评价',
  3: '已退款',
  4: '已取消',
  5: '已评价',
};

// 商家名称映射
const merchantMap = {
  1: '联查商家名称映射（待实现）',
  2: '联查商家名称映射（待实现）'
};

const tabs = [
  { label: '全部', value: -1 },
  { label: '待付款', value: 0 },
  { label: '待收货', value: 1 },
  { label: '待评价', value: 2 },
  { label: '售后/退款', value: 3 }
];
// 在 script setup 顶部定义缓存（可放在 api 目录或 utils，这里简化）

const currentStatus = ref(-1); // -1 表示全部
const orders = ref([]);

const currentStatusLabel = computed(() => {
  return tabs.find(t => t.value === currentStatus.value)?.label || '订单';
});

const filteredOrders = computed(() => {
  if (currentStatus.value === -1) {
    return orders.value;
  }
  return orders.value.filter(order => order.orderStatus === currentStatus.value);
});

const switchTab = (status) => {
  currentStatus.value = status;
};

const getStatusText = (status) => {
  return statusMap[status] || '未知状态';
};

const getMerchantName = (merchantId) => {
  return merchantMap[merchantId] || '其他商家';
};

const getOrderItemCount = (order) => {
  return 1; // 实际项目应通过订单详情接口获取真实商品数量
};

// 时间格式化函数（支持 ISO 字符串或时间戳）
const formatTime = (time) => {
  if (!time) return '—';
  const date = new Date(time);
  if (isNaN(date.getTime())) return '—';
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}`;
};

const goToDetail = (orderId) => {
  // 找到对应的完整 order 对象
  const fullOrder = orders.value.find(o => o.orderId === orderId);
  if (fullOrder) {
    // 缓存起来，key 用 orderId
    orderCache[orderId] = fullOrder;
  }
  uni.navigateTo({
    url: `/pages/orders/order-detail/order-detail?orderId=${encodeURIComponent(orderId)}`
  });
};

const handleSettle = async (orderId) => {
  uni.showLoading({ title: '正在结算...' });
  const success = await settleOrder(orderId); // 调用结算接口
  uni.hideLoading();
  if (success) {
    uni.showToast({ title: '支付成功', icon: 'success' });
    // 更新订单状态或刷新订单列表
	await loadOrders();
  } else {
    uni.showToast({ title: '支付失败', icon: 'none' });
  }
};

const confirmReceive = async (orderId) => {
  uni.showModal({
    title: '确认收货',
    content: '确认货物无损，确认签收',
    success: async (res) => {
      if (res.confirm) {
		uni.showLoading({ title: '加载中...' });
        const success = await confirmOrder(orderId);
		uni.hideLoading();
		if (success) {
		  uni.showToast({ title: '签收成功', icon: 'success' });
		  // 更新订单状态或刷新订单列表
			await loadOrders();
		} else {
		  uni.showToast({ title: '签收失败', icon: 'none' });
		}
      }
    }
  });
};

const goToReview = (orderId) => {
  uni.navigateTo({
    url: `/pages/orders/review-write/review-write?orderId=${orderId}`
  });
};

// 控制台输出 orderId
const logOrderId = (orderId) => {
  console.log('查看的订单ID:', orderId);
  uni.navigateTo({
    url: `/pages/orders/order-detail/order-detail?orderId=${orderId}`
  });
};



// 1. 定义可复用的数据加载函数
const loadOrders = async () => {
  const userId = userManager.user.userId;
  if (!userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    setTimeout(() => uni.switchTab({ url: '/pages/user/user' }), 1000);
    return;
  }

  uni.showLoading({ title: '加载中...' });
  try {
    const data = await getOrderList(userId);
    if (data) {
      orders.value = data.sort((a, b) =>
        new Date(b.createTime) - new Date(a.createTime)
      );
    }
  } finally {
    uni.hideLoading();
  }
};

// 2. 在 onMounted 中调用它（组件挂载时加载）
onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.order-list-page {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.status-tabs {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: #fff;
  padding: 20rpx 0;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.tab-item {
  padding: 10rpx 20rpx;
  font-size: 28rpx;
  color: #666;
}

.tab-item.active {
  color: #007aff;
  font-weight: bold;
}

.order-item {
  background: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
  font-size: 26rpx;
}

.order-header .merchant {
  color: #333;
}

.order-header .status {
  color: #ff6b35;
  font-weight: bold;
}

.order-goods-placeholder {
  margin-bottom: 16rpx;
  color: #999;
  font-size: 26rpx;
}

.order-receiver-info,
.order-time-info {
  margin-bottom: 16rpx;
  font-size: 24rpx;
  color: #666;
}

.receiver-line,
.time-line {
  display: block;
  margin-bottom: 8rpx;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-footer .total {
  font-size: 28rpx;
  color: #e54d42;
  font-weight: bold;
}

.action-buttons {
  display: flex;
  gap: 10rpx;
  align-items: center;
}

.empty-tip {
  text-align: center;
  margin-top: 200rpx;
  color: #999;
  font-size: 28rpx;
}
</style>